package com.example.zegodemo;

import static android.content.Context.MEDIA_PROJECTION_SERVICE;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import im.zego.zegoexpress.ZegoExpressEngine;
import im.zego.zegoexpress.constants.ZegoPublishChannel;
import im.zego.zegoexpress.constants.ZegoVideoBufferType;
import im.zego.zegoexpress.entity.ZegoCustomVideoCaptureConfig;

public class ScreenShareUtil {

    private AppCompatActivity mActivity;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    public MediaProjection mMediaProjection;
    public MediaProjectionManager mMediaProjectionManager;

    private CaptureScreenConnection mConnection;
    private CaptureScreenService.IService mAgent;

    private VideoCaptureScreen mVideoCapture;
    private  ZegoExpressEngine engine;
    public static String TAG="ScreenShareUtil";
    public ScreenShareUtil(AppCompatActivity mActivity,VideoCaptureScreen videoCapture,ZegoExpressEngine engine) {
        this.mActivity = mActivity;
        this.mVideoCapture = videoCapture;
        this.engine=engine;
        intentActivityResultLauncher = mActivity.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                Intent data = result.getData();
                int resultCode = result.getResultCode();
                if (data != null && resultCode == Activity.RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        // Target版本高于等于10.0需要使用前台服务，并在前台服务的onStartCommand方法中创建MediaProjection
                        if (null != mConnection) {
                            Log.e(TAG,"已经绑定了");
                            return;
                        }
                        mConnection = new CaptureScreenConnection();
                        Intent service = new Intent(mActivity, CaptureScreenService.class);
                        service.putExtra("code", resultCode);
                        service.putExtra("data", data);
                        if (mActivity.bindService(service, mConnection, Context.BIND_AUTO_CREATE)) {
                            Log.e(TAG,"bindService成功");
                        } else {
                            Log.e(TAG,"bindService error");
                        }
                    } else {
                        //Target版本低于10.0直接获取MediaProjection
//                        initmMediaProjection(resultCode, data);
                        mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
                        initmMediaProjection();
                    }

                } else {
                    //失败
                    Log.e(TAG, "onActivityResult:MediaProjectionManager error ");
                }
            }
        });
    }

    private class CaptureScreenConnection implements ServiceConnection {
        /**
         * 当与服务连接的调用
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG,"-->:: onServiceConnected");
            // 连接成功后，会把代理人传递过来
            mAgent = (CaptureScreenService.IService) service;
            // 调用服务中的方法，注意，需要先绑定服务
            if (null != mAgent) {
                mMediaProjection = mAgent.callServiceMethod();
            }
            if (null != mMediaProjection) {
                initmMediaProjection();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG,"-->:: onServiceDisconnected");
            mAgent = null;
        }
    }
    public void initmMediaProjection() {
        Log.e(TAG,"设置mMediaProjection");
        if (mMediaProjection==null){
            Log.e(TAG,"mMediaProjection是null");
            return;
        }
        if (mVideoCapture==null){
            Log.e(TAG,"mVideoCapture是null");
            return;
        }
        mVideoCapture.setMediaProjection(mMediaProjection);
        engine.startPublishingStream("pmstream2",
                ZegoPublishChannel.AUX);
    }

    public void startShare() {
        mMediaProjectionManager = (MediaProjectionManager) mActivity.getSystemService(MEDIA_PROJECTION_SERVICE);
        intentActivityResultLauncher.launch(mMediaProjectionManager.createScreenCaptureIntent());
    }
}
